package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import com.itheima.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

	@Reference
	MenuService menuService;

	@RequestMapping("/loginSuccess")
	public String loginSuccess(){
		return "redirect:http://localhost:83/pages/main.html";
	}

	@RequestMapping("/loginFail")
	public String loginFail(){
		return "redirect:http://localhost:83/pages/faillogin.html";
	}

	@RequestMapping("/getUsername")
	@ResponseBody
	public Result getUsername(){
		//从授权框架上下文获取授权对象，再从授权对象获取授权框架用户对象User,最后获取用户名
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Object principal = authentication.getPrincipal();
		if(principal instanceof User){
			User user = (User) principal;
			return new Result(true, MessageConst.GET_USERNAME_SUCCESS,user.getUsername());
		}
		return new Result(false, MessageConst.GET_USERNAME_FAIL);
	}

	@ResponseBody
	@RequestMapping("/getMenuList")
	public Result getMenuList() {
		String username=null;
		//从授权框架上下文获取授权对象，再从授权对象获取授权框架用户对象User,最后获取用户名
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Object principal = authentication.getPrincipal();
		if (principal instanceof User) {
			User user = (User) principal;
			username=user.getUsername();
		}
		List<Map<String,Object>> menuList = menuService.findMenuByUsername(username);
		log.debug("动态菜单成功！"+menuList.toString());
		return new Result(true, "动态菜单成功！", menuList);
	}

}